package com.ln.adoms.action;

import com.ln.adoms.entity.DepartSetting;
import com.ln.adoms.entity.Department;
import com.ln.adoms.entity.DepartmentType;
import com.ln.adoms.entity.Region;
import com.ln.adoms.service.DepartSettingService;
import com.ln.adoms.service.DepartmentService;
import com.ln.adoms.service.DepartmentTypeService;
import com.ln.adoms.service.RegionService;
import com.ln.core.orm.Filtration;
import com.ln.core.orm.Filtration.MatchType;
import com.ln.core.orm.PageData;
import com.ln.core.security.entity.Users;
import com.ln.core.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/adoms/department")
public class DepartmentAction {
    @Resource
    private DepartmentService departmentService;
    @Resource
    private DepartmentTypeService departmentTypeService;
    @Autowired
    private DepartSettingService departSettingService;
    @Autowired
    private RegionService regionService;

    @RequestMapping("/list")
    public ModelMap list(HttpServletRequest request) {
        PageData<Department> pageData = new PageData<Department>();
        // 给pageData设置参数
        WebUtils.setPageDataParameter(request, pageData);
        pageData = departmentService.find(pageData);

        return new ModelMap(pageData);
    }

    @RequestMapping(value = "/new")
    public String addForm(Model model) {
        listTypeAndDepartment(model, null);
        model.addAttribute(new Department());
        List<Region> regions = regionService.findList("parent.id", 0);
        model.addAttribute("regions", regions);
        return "/adoms/department/input";
    }

    @RequestMapping(value = "/edit/{id}")
    public String editForm(@PathVariable("id") Integer id, Model model) {
        Department department = departmentService.find(id);
        model.addAttribute(department);
        listTypeAndDepartment(model, department);
        List<Region> regions = regionService.findList("parent.id", 0);
        model.addAttribute("regions", regions);
        return "/adoms/department/input";
    }

    // 设置表单中的数据：部门类型下拉框，上级部门下拉框
    private void listTypeAndDepartment(Model model, Department department) {
        List<DepartmentType> typeList = departmentTypeService.findAll();
        model.addAttribute("typeList", typeList);
        List<Department> departmentList = departmentService.findAll();
        if (department != null) {
            for (Department d : departmentList) {
                if (d.getId().equals(department.getId())) {
                    department = d;
                }
            }
            departmentList.remove(department);
        }
        model.addAttribute("departmentList", departmentList);
    }

    @RequestMapping(value = "/listDepartmentByType")
    @ResponseBody
    public List<Department> listDepartmentByType(Integer typeId) {
        Filtration filter = new Filtration(MatchType.EQ, typeId, "type.id");
        List<Department> list = departmentService.findList(filter);
        return list;
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(@Valid Department department, BindingResult result, Integer[] brandIds) {
        if (result.hasErrors()) {
            return "/adoms/department/input";
        }
        //保存or更新部门数据
        departmentService.saveOrUpdate(department, brandIds);

        return "redirect:/adoms/department/list";// 重定向
    }

    @RequestMapping(value = "/repeat")
    @ResponseBody
    public boolean repeat(String value, Integer id, String property) {
        try {
            List<Department> departments = departmentService.findList(property, value);
            if (departments != null && departments.size() > 0) {
                if (id != 0) {
                    Department d = departmentService.find(id);
                    if (property.equals("name") && !d.getName().equals(value)) {
                        return false;
                    } else if (property.equals("code") && !d.getCode().equals(value)) {
                        return false;
                    }
                } else {
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    @RequestMapping(value = "/delete/{id}")
    public String delete(@PathVariable("id") Integer id) {
        departmentService.delete(id);
        return "redirect:/adoms/department/list";// 重定向
    }

    @RequestMapping(value = "/visible/{id}")
    public String visible(@PathVariable("id") Integer id) {
        departmentService.visible(id);
        return "redirect:/adoms/department/list";// 重定向
    }

    @RequestMapping(value = "/unVisible/{id}")
    public String unVisible(@PathVariable("id") Integer id) {
        departmentService.unVisible(id);
        return "redirect:/adoms/department/list";// 重定向
    }

    @RequestMapping(value = "/setting", method = RequestMethod.GET)
    public String setting(HttpSession session, Model model) {
        Users users = (Users) session.getAttribute("USER");
        DepartSetting orderSetting = departSettingService.getAutoReceiveOrderSetting(users.getDepartment().getId());
        model.addAttribute("orderSetting", orderSetting);
        return "/adoms/department/setting";
    }

    @RequestMapping(value = "/setting", method = RequestMethod.POST)
    public String setting(DepartSetting setting) {
        departSettingService.save(setting);
        return "redirect:/adoms/department/setting";
    }

    @InitBinder
    public void InitBinder(WebDataBinder dataBinder) {
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
    }

}
